package cn.ainit.sys.menu;
/***
 * 开发要点：
 *  1.返回json数据 
	    @RequestMapping("/getAllUser")
	    @ResponseBody	//springMVC 内置注解，返回json数据
	  	public List<User> getAllUser(String uid,HttpServletRequest request){
	  		......
	  		List<User> users = new ArrayList<User>();
	  		...
	  		return columns;
	  	}
 */

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.instrument.Instrumentation;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.ainit.common.ReturnObject;
import cn.ainit.sys.dz.entity.SysDzSource;
import cn.ainit.sys.models.ModelReceiveObj;
import cn.ainit.sys.utils.MD5Util;
import cn.ainit.sys.utils.UUID32;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sun.jmx.snmp.Timestamp;

@Controller
@RequestMapping("/menu")
public class MenuController {
	static Instrumentation inst;
	private MenuManager menuManager;

	@Resource
	public void setMenuManager(MenuManager menuManager) {
		this.menuManager = menuManager;
	}
	public static Map<String,List> mapList=new HashMap<String, List>();
	public static String formatsStr="";

	@RequestMapping("login")
	@ResponseBody
	public String login(String name,String pass,String login,HttpServletRequest request,HttpSession session,HttpServletResponse response){
		System.out.println("========login()==========开始进入Controller"+new Date());
		String flag = "";
		try {

			StringBuffer sessionSql = new StringBuffer("");
			//将数据写入sys_session
			if (name != null &&  pass != null ) {
				//对密码进行加密
				pass = MD5Util.encode(pass);
				//httpRequert的键
				String key =name+pass;
				String sql = " select o_exist, o_id,o_name,bumen from bs_operators t where o_name = ? and o_pass_word = ? ";
				SessionObj loginObj = menuManager.existOperator(sql,name,pass);
				System.out.println("============login()=============existOperator");
				if(loginObj != null){      
					try {
						if(loginObj.getO_exist().equals("0")){
							return "yglz";
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					List<Map<String, Object>> list=	menuManager.querySessionInfo(loginObj.getUid());
					if(list.size()>0){
						boolean b=menuManager.delSessionInfo_(loginObj.getUid());
					}
					//name //用户名
					String sta = "st001";
					String depid = loginObj.getDepid();//部门
					//session 中的数据
					session.setAttribute(SessionCont.name, loginObj.getName());
					session.setAttribute("loginName", loginObj.getName());
					System.out.println("loginObj.getName():"+ loginObj.getName());
					session.setAttribute(SessionCont.DEPART_ID, depid==null?"":depid);
					session.setAttribute(SessionCont.uid, loginObj.getUid());
					session.setAttribute(SessionCont.STATION_ID, sta==null?"":sta);  
					request.setAttribute("login",login);
					//登录根据session  id保存key 不可删除   退出时用
					session.setAttribute(session.getId(), key);
					session.setAttribute("uinfo", loginObj);

					Calendar c = Calendar.getInstance();
					int hour = c.get(Calendar.HOUR_OF_DAY); 
					if(6<=hour &&hour<12){
						session.setAttribute("time", "上午好");
					}
					if(12<=hour &&hour<19){
						session.setAttribute("time", "下午好");
					}
					if(19<=hour &&hour<24){
						session.setAttribute("time", "晚上好");
					}

					//							List<SysLeftMenu> menus=menuManager.getAllMenus();
					flag = "success";
					String ip = "127.0.0.1";    //获取真实的ip
					loginObj.setSessionId(UUID32.newGuid());
					loginObj.setIp(ip);
					loginObj.setSta(sta);
					loginObj.setDepid(depid);
					//						menuManager.writeSession(sessionSql,loginObj);//登陆日志流水						//把用户名与加密后的密码当键requers当值
					session.setAttribute("key", key);
					//在数据库中对数据进行保存
					SysSessionContorl sessionContorl=new SysSessionContorl();
					sessionContorl.setId(key);
					sessionContorl.setIsOnline("T");
					sessionContorl.setLoginIp(request.getRemoteHost());
					sessionContorl.setUserName(loginObj.getName());
					sessionContorl.setSessionId(request.getSession().getId());
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String time=df.format(new Date());
					System.out.println(new Timestamp(df.parse(time).getTime()));
					sessionContorl.setLoginTime(new Date());
					sessionContorl.setUserid(loginObj.getUid());
					Boolean boolean1=menuManager.saveSessionContorl(sessionContorl);

					//设置cookie
					Cookie cookie=new Cookie("user", URLEncoder.encode(loginObj.getName(),"utf-8"));
					cookie.setPath(request.getContextPath());
					//Cookie cookiep=new Cookie("pwd", pass);
					//cookiep.setPath(request.getContextPath());
					cookie.setMaxAge(5*365*24*60*60);
					response.addCookie(cookie);
					//				        response.addCookie(cookiep);

				}else{
					flag = "fail";
					return flag; //用户输入的用户名和密码不匹配的时候不能登陆
				}
			}else {
				flag = "fail";   
			}
		} catch (Exception e) {
			e.printStackTrace();
			flag = e.getMessage();
		}
		return flag;
	}

	@RequestMapping("cookie")
	@ResponseBody
	public List cookie(HttpServletRequest request) {
		List list=new ArrayList();
		String value=null;
		Cookie[] cookies = request.getCookies();
		for(Cookie c :cookies ){
			if(c.getName().equals("user")){
				try {
					value=URLDecoder.decode(c.getValue(),"utf-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}

			}
		}
		list.add(value);
		return list;
	}


	/***
	 * 获取用户真实的IP地址
	 * @param request
	 * @return
	 */
	public String getIRealIPAddr(HttpServletRequest request) {      //修改squid.conf 的配制文件　forwarded_for的值
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || "null".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || "null".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || "null".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/***
	 * 登录完成之后进入 获取有权限的模块
	 * @param request
	 * @param session
	 * @return
	 * @author Xuzq
	 * @date 2014-8-29 下午03:20:54
	 */
	@RequestMapping("/getAllMenu")
	public String getAllMenu(HttpServletRequest request,HttpSession session){
		try {
			String flag = "";
			flag = "success";
			String ip = request.getRemoteAddr();
			Object object=menuManager.getLeftMenu((String) session.getAttribute(SessionCont.uid));
			request.setAttribute("menus", menuManager.getLeftMenu((String) session.getAttribute(SessionCont.uid)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/pages/index";
	}


	/***
	 * 根据左侧菜单栏的Id,得到用户的子系统的权限
	 * @param request
	 * @param session
	 * @return
	 * @author cff
	 * @date 2014-8-29 下午03:20:54
	 */
	@RequestMapping("/loadSubSysRight")
	@ResponseBody
	public Object getSubSysRight(String menuId,HttpServletRequest request,HttpSession session){
		Object object=null;
		try {
			String flag = "";
			flag = "success";
			object=menuManager.getSubSysRight((String) session.getAttribute(SessionCont.uid), menuId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}

	@RequestMapping("/getMenu")
	public String getMenu(String funcId,HttpServletRequest request){
		try {
			List<SysFunctions> sysFunctions = menuManager.getMenuById(funcId);
			Map map = new HashMap();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/test/editUser";
	}

	/***
	 * 获取用户的模块权限（左侧菜单V2.0）
	 * @param sid
	 * @param request
	 * @return
	 * @author Xuzq
	 * @date 2014-8-29 上午10:42:45
	 */
	@RequestMapping("/getMenuMap")
	@ResponseBody	
	public Map<String, List<SysFunctions>>  getLeftMenus(String sid,HttpServletRequest request){
		Map<String, List<SysFunctions>> menuMap1 = new HashMap<String, List<SysFunctions>>();
		return menuMap1;
	}




	
	/***
	 * 刷新所有缓存
	 * @return
	 */
	@RequestMapping("loadAllDz")
	@ResponseBody
	public Map<String, List> loadDzSource(String isALoad){
		if(isALoad!=null&&"true".equals(isALoad)){
			mapList=new HashMap<String, List>();
			List<SysDzSource> dzSources = new ArrayList<SysDzSource>();
			try {
				dzSources = menuManager.getAllDzSource();
				for (int i = 0; i < dzSources.size(); i++) {
					try {
						mapList.remove(dzSources.get(i).getDzId());
						mapList.put(dzSources.get(i).getDzId(),menuManager.loadDzList(dzSources.get(i).getSqlText(),dzSources.get(i).getShowPk(),dzSources.get(i).getShowName()));
					} catch (Exception e) {
						e.printStackTrace();
						System.out.println("对照信息"+dzSources.get(i).getDzId()+"配置不正确"+dzSources.get(i).getSqlText());
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return mapList;
	}

	@RequestMapping("loadDzDataByDBI")
	@ResponseBody
	public Map<String, List> loadDzDataByDBI(String isALoad, String dbi){
		Map<String,List> loadDzDataByDBIMapList=new HashMap<String, List>();
		if(isALoad!=null&&"true".equals(isALoad)){
			List<SysDzSource> dzSources = new ArrayList<SysDzSource>();
			try {
				dzSources = menuManager.getDzSourceByDBI(dbi);
				loadDzDataByDBIMapList = getDzSourceMapList(dzSources);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		mapList.putAll(loadDzDataByDBIMapList);
		return loadDzDataByDBIMapList;
	}

	@RequestMapping("loadDzDataByDBIAndShowpk")
	@ResponseBody
	public Map<String, List> loadDzDataByDBIAndShowpk(String isALoad, String dbi, String showpk){
		Map<String,List> loadDzDataByDBIAndShowpkMapList = new HashMap<String, List>();
		if(isALoad!=null&&"true".equals(isALoad)){
			List<SysDzSource> dzSources = new ArrayList<SysDzSource>();
			try {
				dzSources = menuManager.getDzSourceByDBIAndShowpk(dbi, showpk);
				loadDzDataByDBIAndShowpkMapList = getDzSourceMapList(dzSources);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		mapList.putAll(loadDzDataByDBIAndShowpkMapList);
		return loadDzDataByDBIAndShowpkMapList;
	}

	@RequestMapping("loadDzDataByDBIAndShowpkNotIn")
	@ResponseBody
	public Map<String, List> loadDzDataByDBIAndShowpkNotIn(String isALoad, String dbi, String showpk){
		Map<String,List> loadDzDataByDBIAndShowpkNotInMapList=new HashMap<String, List>();
		if(isALoad!=null&&"true".equals(isALoad)){
			List<SysDzSource> dzSources = new ArrayList<SysDzSource>();
			try {
				dzSources = menuManager.getDzSourceByDBIAndShowpkNotIn(dbi, showpk);
				loadDzDataByDBIAndShowpkNotInMapList = getDzSourceMapList(dzSources);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		mapList.putAll(loadDzDataByDBIAndShowpkNotInMapList);
		return loadDzDataByDBIAndShowpkNotInMapList;
	}

	private Map<String, List> getDzSourceMapList(List<SysDzSource> dzSources){
		Map<String, List> dzMapList = new HashMap<String, List>();
		try {
			for (int i = 0; i < dzSources.size(); i++) {
				try {
					mapList.remove(dzSources.get(i).getDzId());

					dzMapList.remove(dzSources.get(i).getDzId());
					dzMapList.put(dzSources.get(i).getDzId(),menuManager.loadDzList(dzSources.get(i).getSqlText(),dzSources.get(i).getShowPk(),dzSources.get(i).getShowName()));
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("对照信息"+dzSources.get(i).getDzId()+"配置不正确"+dzSources.get(i).getSqlText());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dzMapList;
	}


	/**
	 * 根据单据的DsId刷新缓存数据
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("loadDzDataByDsId")
	@ResponseBody
	public Map<String, List> loadDzDataByDsId(String dsId) throws Exception{
		//判断是不是主明细的表
		List<SysDzSource> dzSources = new ArrayList<SysDzSource>();
		dzSources = menuManager.loadDzDataByDsId(dsId);
		Map<String, List> mapList = new HashMap<String, List>();
		try {
			if(dzSources!=null){
				for (int i = 0; i < dzSources.size(); i++) {
					try {
						mapList.put(dzSources.get(i).getDzId(),menuManager.loadDzList(dzSources.get(i).getSqlText(),dzSources.get(i).getShowPk(),dzSources.get(i).getShowName()));
					} catch (Exception e) {
						e.printStackTrace();
						System.out.println("对照信息"+dzSources.get(i).getDzId()+"配置不正确"+dzSources.get(i).getSqlText());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mapList;
	}




	@RequestMapping("/loadSomeDz")
	@ResponseBody
	public Map<String, List> loadDzSourceOne(String dsId,HttpServletRequest request) throws Exception{
		Map<String, List> mapList = new HashMap<String, List>();
		List<SysDzSource> dzSources = new ArrayList<SysDzSource>();
		try {
			dzSources = menuManager.getDzSourceSome(dsId);
			for (int i = 0; i < dzSources.size(); i++) {
				try {
					mapList.put(dzSources.get(i).getDzId(), menuManager.loadDzList(
							dzSources.get(i).getSqlText(),
							dzSources.get(i).getShowPk(),
							dzSources.get(i).getShowName()));
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("对照信息"+dzSources.get(i).getDzId()+"配置不正确"+dzSources.get(i).getSqlText());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mapList;
	}

	/****
	 * 
	 * @param funcId
	 * @param session
	 * @return
	 * @throws Exception
	 * @author feifei
	 * @date: 2015-5-11 下午03:39:53 
	 */
	@RequestMapping("getUrl")
	@ResponseBody
	public SysFunctions getUrl(String funcId,HttpSession session)throws Exception{
		String uid = (String) session.getAttribute(SessionCont.uid);
		SysFunctions tmp=menuManager.getFunctionById(funcId,uid);
		if( tmp !=null ){
			return tmp;
		}
		return null;
	}



	/***
	 * 系统退出的方法
	 */
	@RequestMapping("/logout")
	@ResponseBody
	public void logout(HttpServletRequest request,HttpSession session){
		try {
			String uid =(String)  session.getAttribute(SessionCont.uid);
			//删除数据库中的登录信息
			boolean b=menuManager.delSessionInfo(uid);
			OnlineUserListener.sessionMap.remove(request.getSession().getId());
			session.removeAttribute(SessionCont.uid);
		} catch (Exception e) {
		}

	}

	/**
	 * 
	 * @Title: stopCourse
	 * @author : FuXiangYi  
	 * @Description: 停止进程
	 * @param sessionid
	 * @return    
	 * @return String 
	 * @date 2014-11-6 上午09:53:14
	 */
	@RequestMapping("stopCourse")
	@ResponseBody
	public String stopCourse( String sessionid){
		boolean b=menuManager.delSessionInfo(sessionid);
		try {
			OnlineUserListener.sessionMap.get(sessionid).invalidate();
			OnlineUserListener.sessionMap.remove(sessionid);
		} catch (Exception e) {
		}

		if(b){
			return "success";
		}


		return "error";
	}



	///////////////////////////////////////////员工权限开始访问的路径/////////////////////////////////////////////////////////////
	/**
	 * 返回jsp的方法（返回的是用户权限的jsp）
	 * 同时返回相应的对象
	 */
	@RequestMapping("/sysRight")
	public String sysRight(ModelReceiveObj modelReceiveObj,HttpServletRequest request,HttpSession session) throws Exception{
		try { 
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 SingleController L.138");
			}
			RightList rightList = new RightList();
			List groupList = this.menuManager.getAllGroup(); //初始化得到所有的权限组
			List<Map<String,Object>> modelList = this.menuManager.getAllMenus(); //初始化得到所有的左侧模块菜单
			//			List dataStoreList = this.menuManager.dsByModualList(modelList.get(0).getMenuId(),"");//初始化得到第一个模块的datastore
			List dataStoreList = this.menuManager.dsByModualList("", ""); //初始化得到所有的function
			List butnList = this.menuManager.butnByDS("", ""); //初始化得到所有的按钮
			List commButnList = this.menuManager.commButn();   //初始化得到所有的通用按钮
			List departList = this.menuManager.getAllDepart(); //初始化得到所有的部门
			rightList.setBumenList(departList);
			rightList.setGroupList(groupList);
			rightList.setModelList(modelList);
			rightList.setDataStroeList(dataStoreList);
			rightList.setButnList(butnList);
			rightList.setCommButnList(commButnList);

			request.setAttribute("m",rightList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (modelReceiveObj.getJspWebUrl() == null || modelReceiveObj.getJspWebUrl().equals("")) {
			modelReceiveObj.setJspWebUrl("/model/single/squery");
		}
		return modelReceiveObj.getJspWebUrl();//"/models/single/squery";
	}
	/**
	 * 返回jsp的方法（返回的是角色组权限的jsp）
	 * 同时返回相应的对象
	 */
	@RequestMapping("/sysRightGroup")
	public String sysRightGroup(ModelReceiveObj modelReceiveObj,HttpServletRequest request,HttpSession session) throws Exception{
		try {
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 SingleController L.138");
			}
			RightList rightList = new RightList();
			//			List groupList = this.menuManager.getAllGroup(); //初始化得到所有的权限组
			List<Map<String,Object>> modelList = this.menuManager.getAllMenus(); //初始化得到所有的左侧模块菜单
			//			List dataStoreList = this.menuManager.dsByModualList(modelList.get(0).getMenuId(),"");//初始化得到第一个模块的datastore
			List dataStoreList = this.menuManager.dsByModualList("", ""); //初始化得到所有的Functions
			List butnList = this.menuManager.butnByDS("", ""); //初始化得到所有查询页面
			List commButnList = this.menuManager.commButn();   //初始化得到所有的通用按钮
			List bumenList=menuManager.getALLbumen();//获取所有的部门

			rightList.setAllBuMen(bumenList);
			//			rightList.setGroupList(groupList);
			rightList.setModelList(modelList);
			rightList.setDataStroeList(dataStoreList);
			rightList.setButnList(butnList);
			rightList.setCommButnList(commButnList);
			request.setAttribute("m",rightList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (modelReceiveObj.getJspWebUrl() == null || modelReceiveObj.getJspWebUrl().equals("")) {
			modelReceiveObj.setJspWebUrl("/model/sysRight/groupToRight");
		}
		return modelReceiveObj.getJspWebUrl();//"/models/single/squery";
	}

	/**
	 * 查询所有的角色组
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-10-7 下午06:50:33
	 */
	@RequestMapping("/groupAll")
	@ResponseBody
	public List groupAll(HttpServletRequest request) throws Exception{
		List list = new ArrayList();
		try {
			list  = this.menuManager.getAllGroup();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * 根据组Id查询这个组中有多少用户 
	 * 并且返回这个组的具体信息
	 * 还返回组中的模块，功能，按钮
	 * @param gId
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-10-7 下午07:38:46
	 */
	@RequestMapping("/groupHUsers")
	@ResponseBody
	public List groupHUser(String gId,HttpServletRequest request) throws Exception{
		List allList = new ArrayList();
		List list = new ArrayList();
		List groupList = new ArrayList();
		List permsList = new ArrayList();
		List NoHaveCurrentRoleUser = new ArrayList();
		try {
			list = this.menuManager.userByGroup(gId);
			allList.add(list);
			groupList = this.menuManager.groupById(gId);
			allList.add(groupList);
			permsList = this.menuManager.mgbByGroup(gId);
			allList.add(permsList); //list里面还是个list(模块，功能，按钮)
			NoHaveCurrentRoleUser = this.menuManager.daoNoHaveCurrentRoleUser(gId);
			allList.add(NoHaveCurrentRoleUser); //list里面还是个list(模块，功能，按钮)
		} catch (Exception e) {
			e.printStackTrace();
		}
		return allList;
	}

	/**
	 * 
	 * @Title: queryQxz
	 * @author : FuXiangYi  
	 * @Description: 根据用户id获取所在的角色组 
	 * @param uid
	 * @param request
	 * @return
	 * @throws Exception    
	 * @return List 
	 * @date 2015-6-17 下午03:42:40
	 */
	@RequestMapping("/qxzByuid")
	@ResponseBody
	public List queryQxz(String uid,HttpServletRequest request) throws Exception{
		List allList = new ArrayList();
		List list = new ArrayList();
		list=menuManager.getQxzByUid(uid);
		allList.add(list);
		return allList;
	}








	/**
	 * 根据模块加载对应的Datastore  （可能要传一个userId，然后进行判断，并且重新查询数据）
	 * @param mId
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-9-3 上午09:15:55
	 */
	@RequestMapping("/dsByModual")
	@ResponseBody
	public List dsByModual(String mId,String oid,HttpServletRequest request) throws Exception{
		List list = new ArrayList();
		List<Map<String, Object>> allDSByModual = new ArrayList<Map<String, Object>>(); 						//所有的该模块的ds
		List<Map<String, Object>> haveDS = new ArrayList<Map<String, Object>>(); 								//拥有的ds
		List<Map<String, Object>> forbidDS = new ArrayList<Map<String, Object>>();
		try {
			if(oid.equals("") || oid == null){
				list = this.menuManager.dsByModualList(mId,oid);
			}else {
				List allDS = new ArrayList();
				allDS = this.menuManager.dsByModualList(mId, oid);//List<List>
				haveDS = (List) allDS.get(0); //have
				list.add(haveDS); 
				forbidDS = (List) allDS.get(2);
				list.add(forbidDS);
				allDSByModual= (List) allDS.get(1); //all
				if(haveDS != null){
					for (int i = 0; i < haveDS.size(); i++) {
						for (int j = 0; j < allDSByModual.size(); j++) {
							if(haveDS.get(i).get("DS_ID").equals(allDSByModual.get(j).get("DS_ID"))){
								allDSByModual.remove(j);
								j--;
							}
						}
					}
				}
				if(forbidDS != null){
					for (int i = 0; i < forbidDS.size(); i++) {
						for (int j = 0; j < allDSByModual.size(); j++) {
							if(forbidDS.get(i).get("DS_ID").equals(allDSByModual.get(j).get("DS_ID"))){
								allDSByModual.remove(j);
								j--;
							}
						}
					}
				}
				list.add(allDSByModual);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * 保存用户和用户组的关系的方法
	 * 保存在sys_right_map表中
	 * @param oid
	 * @param gIds
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-9-3 上午09:17:51
	 */
	@RequestMapping("/saveGroup")
	@ResponseBody
	public String saveGroupUser(String oid,@RequestBody List<String> gIds,HttpServletRequest request,HttpSession session) throws Exception{
		Object uid = session.getAttribute(SessionCont.uid);
		if (uid == null || "".equals(uid.toString())) {
			System.out.println("用户未登录 SingleController L.138");
		}
		String info ="";
		try {
			//添加方法(sys_right_map) 
			info = this.menuManager.saveGroupUser(oid, gIds, uid.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return info;
	}
	/**
	 * 保存用户和模块的关系的方法
	 * 保存在sys_right_user_modual_map表中
	 * @param oid
	 * @param mids
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-9-3 上午09:18:18
	 */
	@RequestMapping("/saveModual")
	@ResponseBody
	public String saveModual(String oid,String mids,HttpServletRequest request,HttpSession session) throws Exception{
		Object uid = session.getAttribute(SessionCont.uid);
		if (uid == null || "".equals(uid.toString())) {
			System.out.println("用户未登录 SingleController L.138");
		}
		String info ="";
		try {
			//添加方法(sys_right_map) 
			info = this.menuManager.saveModualUser(oid, mids, uid.toString());
		} catch (Exception e) {
			e.printStackTrace(); 
		}
		return info;
	}
	/**
	 * 点击用户加载相应的对象返回界面
	 * @param oid
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyy
	 */
	@RequestMapping("/listByUser")
	@ResponseBody
	public RightList listByUser(String oid,HttpServletRequest request) throws Exception{
		RightList rightList = new RightList();
		try {
			List groupList = new ArrayList();
			groupList = this.menuManager.groupByUId(oid);
			rightList.setHaveGroup((List)groupList.get(0));												 //有的组

			List<Map<String,Object>> haveModualList = new ArrayList<Map<String,Object>>(); 
			haveModualList = this.menuManager.modualByUId(oid);				 							 //有的模块
			rightList.setHaveModual(haveModualList);        											 //将有的模块放入返回对象中
			List dbList = new ArrayList();
			dbList = this.menuManager.gbByUserId(oid);												     //功能以及按钮的集合
			rightList.setDataStroeList((List)dbList.get(0)== null?new ArrayList():(List)dbList.get(0));  //将功能放入返回对象中
			rightList.setButnList((List)dbList.get(1)== null?new ArrayList():(List)dbList.get(1)); 		 //将按钮放入返回对象中

		} catch (Exception e) {
			e.printStackTrace();
		}
		return rightList;
	}
	/**
	 * 点击用户角色的选项卡时，根据用户来加载用户所拥有的权限
	 *  目的是用户组权限修改之后刷新模块权限显示
	 * @param oid
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyy
	 */
	@RequestMapping("/permsByUser")
	@ResponseBody
	public RightList modualByUser(String oid,HttpServletRequest request) throws Exception{
		RightList rightList = new RightList();
		try {
			List<Map<String,Object>> haveModualList = this.menuManager.modualByUId(oid);				 //有的模块
			rightList.setHaveModual(haveModualList);        											 //将有的模块放入返回对象中
			List dbList = this.menuManager.gbByUserId(oid);												 //功能以及按钮的集合
			rightList.setDataStroeList((List)dbList.get(0)== null?new ArrayList():(List)dbList.get(0));  //将功能放入返回对象中
			rightList.setButnList((List)dbList.get(1)); 	
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rightList;
	}
	/**
	 * 点击所属角色组的选项卡时，根据用户来加载用户所属的角色组
	 *  目的是用户组权限修改之后刷新模块权限显示
	 * @param oid
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyy
	 */
	@RequestMapping("/groupByUser")
	@ResponseBody
	public RightList groupByUser(String oid,HttpServletRequest request) throws Exception{
		RightList rightList = new RightList();
		try {
			List groupList = new ArrayList();
			groupList = this.menuManager.groupByUId(oid);
			rightList.setHaveGroup((List)groupList.get(0));												 //有的组
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rightList;
	}
	/**
	 * 保存功能
	 * @param mId
	 * @param oid
	 * @param dsList
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-9-10 上午10:31:15
	 */
	@RequestMapping("/dsSavegn")
	@ResponseBody
	public String dsSave(String mId,String oid,@RequestBody List<Map<String,String>> dsList,HttpServletRequest request,HttpSession session) throws Exception{
		String result="";
		try {
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 SingleController L.138");
			}
			result = this.menuManager.saveDSGN(mId, oid, dsList, uid.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 根据dsId得到一个sql
	 * @param dsId
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-9-10 下午05:03:37
	 */
	@RequestMapping("/sqlForModual")
	@ResponseBody
	public ReturnObject sqlForMod(String dsId,HttpServletRequest request) throws Exception{
		ReturnObject returnObject = new ReturnObject();
		String sqlText = "";
		try {
			returnObject = this.menuManager.sqlByModual(dsId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnObject;
	}
	/**
	 * 数据权限中测试sql是否正确的方法
	 * @param sql
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-9-10 下午03:11:41
	 */
	@RequestMapping("/execSql")
	@ResponseBody
	public boolean execSql(String sql,HttpServletRequest request) throws Exception{
		boolean flag = false;
		try {
			flag = this.menuManager.executSql(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	/**
	 * 保存数据权限
	 * @param dsId
	 * @param whereStr
	 * @param oid
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-9-15 下午05:49:35
	 */
	@RequestMapping("/saveWhereSql")
	@ResponseBody
	public boolean saveWhereSql(String dsId,String whereStr,String oid,HttpServletRequest request,HttpSession session) throws Exception{
		boolean flag = false;
		try {
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 SingleController L.138");
			}
			flag = this.menuManager.saveWhere(dsId, whereStr, oid, uid.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	/**
	 * 根据模块加载对应的Datastore  （可能要传一个userId，然后进行判断，并且重新查询数据）
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-9-3 上午09:15:55
	 */
	@RequestMapping("/butnByDS")
	@ResponseBody
	public List butnByDS(String dsId,String oid,HttpServletRequest request) throws Exception{
		List list = new ArrayList();
		List<Map<String, Object>> allButnList = new ArrayList<Map<String, Object>>(); //所有的该模块的ds
		List<Map<String, Object>> haveButn = new ArrayList<Map<String, Object>>(); //拥有的ds
		List<Map<String, Object>> forbidButn = new ArrayList<Map<String, Object>>();
		try {
			if(oid.equals("") || oid == null){
				list = this.menuManager.butnByDS(dsId, oid);
			}else {
				List allButn = new ArrayList();
				allButn = this.menuManager.butnByDS(dsId, oid);//List<List>
				haveButn = (List) allButn.get(0); //have
				list.add(haveButn); 
				forbidButn = (List) allButn.get(2);
				list.add(forbidButn);
				allButnList= (List) allButn.get(1); //all
				if(haveButn != null){
					for (int i = 0; i < haveButn.size(); i++) {
						for (int j = 0; j < allButnList.size(); j++) {
							if(allButnList.get(j).get("BUT_CODE").equals(haveButn.get(i).get("BUT_CODE"))){
								allButnList.remove(j);
								j--;
							}
						}
					}
				}
				if(forbidButn != null){
					for (int i = 0; i < forbidButn.size(); i++) {
						for (int j = 0; j < allButnList.size(); j++) {
							if(allButnList.get(j).get("BUT_CODE").equals(forbidButn.get(i).get("BUT_CODE"))){
								allButnList.remove(j);
								j--;
							}
						}
					}
				}
				list.add(allButnList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * 保存  按钮
	 * @param dsId
	 * @param oid
	 * @param butnList
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-9-18 上午11:33:51
	 */
	@RequestMapping("/dsSaveButn")
	@ResponseBody
	public String dsSaveButn(String dsId,String oid,@RequestBody List<Map<String,String>> butnList,HttpServletRequest request,HttpSession session) throws Exception{
		String result="";
		try {
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 SingleController L.138");
			}
			result = this.menuManager.saveDSButn(dsId, oid, butnList, uid.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 根据组得到组中的模块，功能，按钮
	 * @param gid
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-9-26 上午10:21:31
	 */
	@RequestMapping("/mgbByGroup")
	@ResponseBody
	public List mdbByGroup(String gid,HttpServletRequest request) throws Exception{
		List list = new ArrayList();
		try {
			list = this.menuManager.mgbByGroup(gid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * 根据组得到组中的模块，功能，按钮
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-9-26 上午10:21:31
	 */
	@RequestMapping("/mgbByGroupNo")
	@ResponseBody
	public List mdbByGroupNo(String qxgid,@RequestBody List<String> gidList,HttpServletRequest request) throws Exception{
		List list = new ArrayList();
		try {
			if(gidList.size() == 0){
				list = this.menuManager.mgbByGroup(qxgid);
			}else {
				list = this.menuManager.mgbByGroupQX(qxgid, gidList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * 保存或者修改组信息
	 * @param gId
	 * @param gName
	 * @param gLevel
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-10-10 上午09:56:18
	 */
	@RequestMapping("/execGroup")
	@ResponseBody
	public boolean saveGroupExec(String gId,String gName,String gLevel,HttpServletRequest request,HttpSession session) throws Exception{
		boolean flag = false;
		try {
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 SingleController L.138");
			}
			flag = this.menuManager.execGroup(gId, gName, gLevel, uid.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	/**
	 * 保存组权限
	 * @param gId
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-10-11 下午03:30:46
	 */
	@RequestMapping("/saveGroupPerms")
	@ResponseBody
	public boolean saveGroupPerms(String gId,String allList,HttpServletRequest request,HttpSession session) throws Exception{
		boolean flag = false;
		try {
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 SingleController L.138");
			}
			//往缓存表中插数据
			flag = this.menuManager.saveGroupPerms(gId, allList,uid.toString());
			if (flag) {
				//执行一个存储过程将缓存表中的数据插入到正式表中，然后将缓存表中的数据删除
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	/**
	 * 保存用户权限
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-10-11 下午03:30:46
	 */
	@RequestMapping("/saveUserPerms")
	@ResponseBody
	public boolean saveUserPerms(String oid,@RequestBody PermsGroup allList,HttpServletRequest request,HttpSession session) throws Exception{
		boolean flag = false;
		try {
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 SingleController L.138");
			}
			//往缓存表中插数据
			flag = this.menuManager.saveUserPerms(oid, allList,uid.toString());
			return true;
		}catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	/**
	 * 根据输入的值查出所有的模块，功能，按钮
	 * @param valStr
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/searchPerms")
	@ResponseBody
	public RightList searchPerms(String valStr,String oid,HttpServletRequest request) throws Exception{
		RightList rightList = new RightList();
		try {
			//返回相应的list
			rightList = this.menuManager.findPerms(valStr);
			if(!"".equals(oid) && oid != null){
				List<Map<String,Object>> haveModualList = this.menuManager.modualByUId(oid);				 //有的模块
				rightList.setHaveModual(haveModualList);        											 //将有的模块放入返回对象中
				List dbList = this.menuManager.gbByUserId(oid);												 //功能以及按钮的集合
				rightList.setHaveFuncs((List)dbList.get(0)== null?new ArrayList():(List)dbList.get(0));      //将功能放入返回对象中
				rightList.setHaveButns((List)dbList.get(1)== null?new ArrayList():(List)dbList.get(1)); 	 //将按钮放入返回的对象中
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rightList;
	}
	/**
	 * 保存模糊查询出的模块，功能，按钮
	 * @param oid
	 * @param allList
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveSearchPerms")
	@ResponseBody
	public boolean saveFindPerms(String oid,@RequestBody PermsGroup allList,HttpServletRequest request,HttpSession session) throws Exception{
		boolean flag = false;
		try {
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 SingleController L.138");
			}
			//往缓存表中插数据
			flag = this.menuManager.saveFindUserPerms(oid, allList,uid.toString());
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	/**
	 * 根据输入的值查出所有的模块，功能，按钮
	 * @param valStr
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/searchGroupPerms")
	@ResponseBody
	public RightList searchGroupPerms(String valStr,String gid,HttpServletRequest request) throws Exception{
		RightList rightList = new RightList();
		List list = new ArrayList();
		try {
			//返回相应的list
			rightList = this.menuManager.findPerms(valStr);
			if(!"".equals(gid) && gid != null){
				list = this.menuManager.mgbByGroup(gid);
				rightList.setHaveModual((List)list.get(0)== null?new ArrayList():(List)list.get(0));     //将功能放入返回对象中 											 //将有的模块放入返回对象中
				rightList.setHaveFuncs((List)list.get(1)== null?new ArrayList():(List)list.get(1));      //将功能放入返回对象中
				rightList.setHaveButns((List)list.get(2)== null?new ArrayList():(List)list.get(2)); 	 //将按钮放入返回的对象中
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rightList;
	}
	/**
	 * 保存模糊查询出的模块，功能，按钮
	 * @param allList
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveFdGroupPerms")
	@ResponseBody
	public boolean saveFdGroupPerms(String gid,@RequestBody PermsGroup allList,HttpServletRequest request,HttpSession session) throws Exception{
		boolean flag = false;
		try {
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 SingleController L.138");
			}
			//往缓存表中插数据
			flag = this.menuManager.saveFindGroupPerms(gid, allList,uid.toString());
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 
	 * @Title: getUserInfo
	 * @author : FuXiangYi  
	 * @Description: 获取当前登录人的信息
	 * @return    
	 * @return boolean 
	 * @date 2014-12-23 下午02:01:20
	 */
	@RequestMapping("uInfo")
	@ResponseBody
	public Map<String, Object> getUserInfo(HttpSession session){
		List<Map<String, Object>> list =menuManager.getLoinUserInfo(session.getAttribute(SessionCont.uid));
		return list.get(0);
	}

	/**
	 * 
	 * @Title: seveRoleGoopUserInfo
	 * @author : FuXiangYi  
	 * @Description:  保存角色组人信息
	 * @param gId
	 * @param insertID
	 * @param delID
	 * @param session
	 * @return    
	 * @return String 
	 * @date 2015-5-11 下午05:27:10
	 */
	@RequestMapping("saveRoleGoopUser")
	@ResponseBody
	public String seveRoleGoopUserInfo(String gId,String insertID,String delID,HttpSession session){

		if(menuManager.SveInserROleGoopUser(gId,insertID,delID))
		{
			return "success";
		}
		return "error";
	}
	@RequestMapping("conditionQueryBumen")
	@ResponseBody
	public RightList conditionQueryBumen(RightList riList){

		riList=	menuManager.SvequeryInfo(riList);

		return riList;
	}


	/*检查服务器是否正常连接*/
	@RequestMapping("badlog")
	@ResponseBody
	public void badlog(HttpServletRequest request,HttpSession session,HttpServletResponse response){
		System.out.println("badlog");
		try {
			request.setCharacterEncoding( "UTF-8");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		response.setCharacterEncoding( "UTF-8");
		response.setContentType( "application/json;charset=utf-8" );

		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}


		out.print("0");
		out.close();


	}






}







